<template>
  <div id="app">
    <table
      border="1"
      width="600"
      style="border-collapse: collapse"
    >
      <caption>
        <h3>购物车</h3>
      </caption>
      <thead>
        <tr>
          <th>
            <input
              type="checkbox"
              :checked="isAll"
              @change="toggle"
              /><span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- <MyTr/> -->

        <my-tr
          v-for="(obj, index) in goodList"
          :key="index"
          :goodsObj="obj"
          :index="index"
          @del="del"
          />
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">
            {{ total }}
          </td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import MyTr from './components/MyTr'
export default {
  components: { MyTr },
  data() {
    return {
      goodList: [
        {
          name: "诸葛亮",
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: "蔡文姬",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: "妲己",
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: "鲁班",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    };
  },
  computed: {
    isAll() {
      return this.goodList.every(item => item.checked)
    },
    total() {
      return this.goodList.reduce((sum, obj) => {
        if(obj.checked) {
          sum += obj.price * obj.num
        }
        return sum
      }, 0)
    }
  },
  methods: {
    toggle(e) {
      const { checked } = e.target
      this.goodList.forEach(item => item.checked = checked)
    },
    del(i) {
      window.confirm('确定删除么?') && this.goodList.splice(i, 1)
    }
  }
};
</script>

<style>
</style>